<template>
  <div class="app-container">
    <el-form ref="form" label-width="100px">
      <el-row :gutter="10">
        <el-card shadow="always" header="基本信息">
          <el-col :span="12">
            <el-form-item label="所属机构">
              <el-input v-model="iOrgsysname" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型">
              <el-input v-model="iDevicetype" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称">
              <el-input v-model="devicesysname" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备码">
              <el-input v-model="strGrantdevicenum" disabled />
            </el-form-item>
          </el-col>
        </el-card>
        <el-card shadow="always" header="拓展应用">
          <el-transfer
            v-model="addDevApp"
            :titles="['未部署', '已部署']"
            :data="appDevAllArr"
            :left-default-checked="leftDefCheckedApp"
            :right-default-checked="rightDefCheckedApp"
            :props="{key:'iAppnum',label:'strAppname'}"
            @right-check-change="hadle"
          />
        </el-card>
        <el-card shadow="always" header="节目单部署">
          <el-table
            ref="multipleTable"
            :data="programAllArr"
            style="width: 100%;"
            max-height="250"
            border
            @select="selectlClick"
          >
            <!-- @selection-change="handleSelectionChange"
            @row-click="clickRow"
            @setCurrentRow="setCurrentRow"
            @cell-click="cellClick"-->
            <el-table-column type="selection" width="55" />
            <el-table-column prop="strUsername" label="节目单名称" />
            <el-table-column prop="countnum" label="素材数量" />
            <el-table-column prop="strCycle" label="播放周期" />
            <el-table-column prop="time" label="有效期">
              <template slot-scope="{row}">{{ row.strStartdate }}/{{ row.strEnddate }}</template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card shadow="always" header="热销产品部署">
          <el-transfer
            v-model="addProduct"
            :titles="['未选产品', '已选产品']"
            :data="productAllArr"
            :left-default-checked="leftDefCheckedPrut"
            :right-default-checked="rightDefCheckedPrut"
            :props="{key:'productnum',label:'strProductname'}"
            @right-check-change="hancle"
          />
        </el-card>
        <el-card shadow="always">
          <div style="text-align: right;">
            <el-button type="primary" @click="handlePublish">发布</el-button>
          </div>
        </el-card>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getAppByDevId,
  getProgramByDevId,
  getPructByDevId,
  getAppByorgNum,
  getprctByorgNum,
  getProgmByorgNum
} from '@/api/devices'
import { ReleasePrograms, getDetaultapp } from '@/api/addTag'
import { uniqueIPrograms } from '../../api/devices/index'

export default {
  name: 'Publish',
  data() {
    return {
      defaultApp: '',
      strGrantdevicenum: this.$route.query.strGrantdevicenum,
      iOrgsysname: this.$route.query.strOrgname, // 所属机构
      devicesysname: this.$route.query.strDevicename, // 设备名称
      iDevicetype: this.$route.query.strValue, // 设备类型
      fullscreenLoading: false,
      addDevApp: [], // 添加拓展应用
      addProduct: [], // 添加产品
      multipleSelection: [], // 添加节目单
      appDevAllArr: [], // 所有拓展应用
      appDevBindArr: [], // 绑定拓展应用
      programAllArr: [], // 所有节目单
      programBindArr: [], // 绑定节目单
      productAllArr: [], // 所有热销产品
      productBindArr: [], // 绑定热销产品
      rightDefCheckedApp: [], // 右边选中应用
      leftDefCheckedApp: [], // 左边选中应用
      rightDefCheckedPrut: [], // 右边选中产品
      leftDefCheckedPrut: [], // 左边选中产品
      compareArr: []
    }
  },
  mounted() {},
  created() {
    if (JSON.stringify(this.$route.query) === '{}') {
      this.$router.push('/termina/publishlist')
    } else {
      this.fetchlist(
        this.$route.query.iDevicesysnum,
        this.$route.query.iOrgsysnum
      )
    }
  },
  methods: {
    // 两个数组比较，返回index arr2 所有 arr1 绑定
    includes(arr1, arr2) {
      // console.log(arr1)
      // console.log(arr2)
      if (arr1 === undefined || arr2 === undefined) {
        return false
      }
      if (arr1.length === 0 && arr2.length === 0) {
        return false
      }
      var lenArr = []
      for (var i = 0; i < arr2.length; i++) {
        var obj = arr2[i]
        var num = obj.programsysnum
        for (var j = 0; j < arr1.length; j++) {
          var aj = arr1[j]
          var n = aj.programsysnum
          if (n === num) {
            lenArr.push(i)
            break
          }
        }
      }
      return lenArr
    },
    fetchlist(iDevicesysnum, iOrgsysnum) {
      Promise.all([
        // 所有应用'101101101'
        getAppByorgNum({ iOrgsysnum }).then(res => {
          // console.log('所有应用', res)
          console.log(res.data)
          console.log(res)
          this.appDevAllArr = res.data === undefined ? [] : res.data
        }),
        getAppByDevId({ iDevicesysnum }).then(res => {
          // console.log('绑定应用', res)
          this.appDevBindArr = res.data === undefined ? [] : res.data
          this.addDevApp = res.data && res.data.map(v => v.iAppnum)
        }),
        getprctByorgNum({ iOrgsysnum }).then(res => {
          // console.log('所有产品', res)
          this.productAllArr = res.data === undefined ? [] : res.data
        }),
        getPructByDevId({ iDevicesysnum }).then(res => {
          // console.log('绑定产品', res)
          this.productBindArr = res.data === undefined ? [] : res.data
          this.addProduct = res.data && res.data.map(v => v.productnum)
        }),
        // 所有节目单
        getProgmByorgNum({ iOrgsysnum }).then(res => {
          console.log('所有节目单', res)
          this.programAllArr = res.data === undefined ? [] : res.data
        }),
        // 绑定节目单
        getProgramByDevId({ iDevicesysnum }).then(res => {
          console.log('绑定节目单', res)
          // console.log(res.data)
          this.programBindArr = res.data === undefined ? [] : res.data
          this.multipleSelection = res.data === undefined ? [] : res.data
        }),
        // 获取默认应用
        getDetaultapp({ iDevicetype: 1 }).then(res => {
          this.defaultApp = res.data === undefined ? [] : res.data
          // res.data && res.data.map(v => v.jcappname).toString()
        })
      ])
        .then(res => {
          this.$nextTick(_ => {
            this.rightDefCheckedApp =
              this.addDevApp === undefined ? [] : this.addDevApp

            this.rightDefCheckedPrut =
              this.addProduct === undefined ? [] : this.addProduct

            this.defaultApp.forEach(item =>
              this.appDevAllArr.push({
                iAppnum: item.jcappid,
                strAppname: item.jcappname + '(基础应用)'
              })
            )
          })
          const obj = {}
          let allProgram = this.programAllArr.concat(this.programBindArr)
          console.log('allProgram', allProgram)
          allProgram = allProgram.reduce((cur, next) => {
            obj[next.programsysnum]
              ? ''
              : (obj[next.programsysnum] = true && cur.push(next))
            return cur
          }, [])
          this.programAllArr = allProgram
          const resultArr = this.includes(
            this.programBindArr,
            this.programAllArr
          )

          if (!resultArr) {
            return false
          }
          // 默认勾选节目单
          this.$nextTick(() => {
            resultArr.map(i => {
              // 默认选中
              this.$refs.multipleTable.toggleRowSelection(
                this.programAllArr[i],
                true
              )
            })
          })
        })
        .catch(err => {
          console.log('请求失败', err)
        })
    },
    selectlClick(select, row) {
      // console.log(select)

      // console.log(row)

      if (select) {
        select.forEach(r => {
          this.$refs.multipleTable.toggleRowSelection(r, true)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
      // if (this.compareArr.length > 2) {
      //   this.multipleSelection = select
      //   return false
      // }

      // if (this.programAllArr.length === 1) {
      //   this.multipleSelection = select
      // }

      this.multipleSelection = select

      // const val = this.compareArr
      const val = this.multipleSelection
      if (val.length > 2) {
        return false
      }
      if (val.length > 1) {
        let uniqueBool = true
        if (
          this.multipleSelection[0].programsysnum === this.multipleSelection[1].programsysnum
        ) {
          this.multipleSelection = select
          uniqueBool = false
        }
        // false 点击同一个
        if (uniqueBool) {
          uniqueIPrograms({
            iProgramsysnum1: val[0].programsysnum,
            iProgramsysnum2: val[1].programsysnum
          })
            .then(res => {
              this.multipleSelection = select
              // this.compareArr.map(row => this.multipleSelection.push(row))
            })
            .catch(err => {
              console.log(err)
              // val.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(val.splice(-1)[0])
              // })
              // this.compareArr = select
            })
        }
      }
    },
    handlePublish() {
      const programsysnumstring = []

      this.multipleSelection.map(item => {
        programsysnumstring.push(item.programsysnum)
      })
      // 新增 id add 1 应用{'1':1,id:'1,2,3'}
      const listQuery = {
        iOrgsysnum: this.$route.query.iOrgsysnum,
        iDevicesysnum: this.$route.query.iDevicesysnum,
        strDevicename: this.devicesysname,
        iDevicetype: this.$route.query.iDevicetype,
        appsysnums:
          this.addDevApp === undefined ? '' : this.addDevApp.toString(),
        programsysnums: programsysnumstring.toString(),
        productsysnums:
          this.addProduct === undefined ? '' : this.addProduct.toString()
      }
      ReleasePrograms(listQuery).then(res => {
        // console.log(res)
        this.$message({
          type: 'success',
          message: '发布成功',
          onClose: () => {
            this.$router.go(-1)
          }
        })
      })
    },
    hadle(val) {
      console.log(val)
    },
    hancle(val) {
      console.log(val)
    }
  }
}
</script>

<style lang="scss" scoped>
.label {
  height: 36px;
  line-height: 36px;
  width: 100px;
}
.app-container {
  background-color: #f5f5f5;
}
/deep/ .el-card {
  margin-bottom: 0.67em;
}
/deep/ .el-table__header-wrapper .el-checkbox {
  //找到表头那一行，然后把里面的复选框隐藏掉
  display: none;
}
</style>
